package com.portal.settings;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

@Slf4j
class SettingsContentUtils {


    static Object parseValue(String value, Class<?> type, Type generic) {
        if (value == null) {
            return null;
        }
        /* handle primitive type */
        if (type.isPrimitive()) {
            if (int.class.equals(type)) {
                return Integer.parseInt(value);
            } else if (boolean.class.equals(type)) {
                return Boolean.parseBoolean(value);
            } else if (long.class.equals(type)) {
                return Long.parseLong(value);
            } else if (double.class.equals(type)) {
                return Double.parseDouble(value);
            } else if (float.class.equals(type)) {
                return Float.parseFloat(value);
            } else if (byte.class.equals(type)) {
                return Byte.parseByte(value);
            } else if (short.class.equals(type)) {
                return Short.parseShort(value);
            } else if (char.class.equals(type)) {
                char[] array = value.toCharArray();
                return array.length > 0 ? array[0] : null;
            }
            return null;
        }

        if (String.class.isAssignableFrom(type)) {
            return value;
        }

        try {
            return JSON.parseObject(value, generic);
        } catch (Exception e) {
            log.error("parseObject setting value exception", e);
            return null;
        }
    }

    static String stringifyValue(Object value, Class<?> type, Type generic) {
        if (value == null) {
            return null;
        }
        /* handle primitive type */
        if (type.isPrimitive()) {
            if (int.class.equals(type)) {
                return Integer.toString((Integer) value);
            } else if (boolean.class.equals(type)) {
                return Boolean.toString((Boolean) value);
            } else if (long.class.equals(type)) {
                return Long.toString((Long) value);
            } else if (double.class.equals(type)) {
                return Double.toString((Double) value);
            } else if (float.class.equals(type)) {
                return Float.toString((Float) value);
            } else if (byte.class.equals(type)) {
                return Byte.toString((Byte) value);
            } else if (short.class.equals(type)) {
                return Short.toString((Short) value);
            } else if (char.class.equals(type)) {
                return String.valueOf((char) value);
            }
            return null;
        }

        if (String.class.isAssignableFrom(type)) {
            return (String) value;
        }

        try {
            return JSON.toJSONString(value);
        } catch (Exception e) {
            log.error("parseObject setting value exception", e);
            return null;
        }
    }

}
